package com.suredy.app.project.service;

import javax.transaction.Transactional;

import org.apache.commons.lang3.StringUtils;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Service;

import com.suredy.app.project.model.Contract;
import com.suredy.core.service.BaseSrvWithEntity;

@Service
public class ContractSrv extends BaseSrvWithEntity<Contract> {

	public ContractSrv() {
		this.addAnDefOrder("type", true);
		this.addAnDefOrder("no", true);
	}

	@Override
	public DetachedCriteria getDc(Contract t) {
		DetachedCriteria dc = super.getDc(t);

		if (t == null)
			return dc;

		if (!StringUtils.isBlank(t.getId())) {
			dc.add(Restrictions.eq("id", t.getId()));
		}
		if (!StringUtils.isBlank(t.getNo())) {
			dc.add(Restrictions.eq("no", t.getNo()));
		}
		if (!StringUtils.isBlank(t.getName())) {
			dc.add(Restrictions.like("name", t.getName(), MatchMode.ANYWHERE));
		}
		if (t.getProject() != null) {
			dc.add(Restrictions.eq("project", t.getProject()));
		}
		if (t.getMainContract() != null) {
			dc.add(Restrictions.eq("mainContract", t.getMainContract()));
		}

		return dc;
	}

	@Transactional
	public int deleteById(String id) {
		if (StringUtils.isBlank(id))
			return 0;

		Contract contract = this.get(id);

		if (contract == null)
			return 0;

		this.delete(contract);

		return 1;
	}

}
